package com.tb.sng.utils.loader
{
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLVariables;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	
	
	/**
	 * 多文件加载类
	 * 
	 * @author 任冬 rending01@snda.com
	 * $Id: MutiFileLoader.as 9 2012-08-12 17:04:32Z rendong237@gmail.com $
	 * @version 1.0
	 */
	/**
	 * 所有文件加载完成 
	 */
	[Event(name="complete",type="flash.events.Event")]
	/**
	 * 进度事件
	 */	
	[Event(name="progress",type="flash.events.ProgressEvent")]
	
	/**
	 * 安全沙箱错误
	 */	
	[Event(name="security_error",type="flash.events.SecurityErrorEvent")]
	/**
	 * 网络io错误
	 */	
	[Event(name="io_error",type="flash.events.IOErrorEvent")]
	
	public class MutiFileLoader extends EventDispatcher
	{

		/**
		 * 加载的文件列表 
		 */		
		private var files:Array;
		/**
		 * 当前加载到什么文件 
		 */		
		private var loadIndex:int;
		
		public function MutiFileLoader(target:IEventDispatcher=null)
		{
			super(target);
			
			files = [];
			loadIndex= 0;
		}
		
		
		/**
		 * 
		 * @param fileId			文件编号
		 * @param url				加载文件的地址
		 * @param vars				参数,get方式
		 * @param rate				进度占总进度百分比
		 * @param isDisplayObject	是否是可视化对象加载，否则采用URLLoader
		 * @param domain			加载域
		 * @param checkPolicyFile	是否加载策略文件
		 * @param dataFormat		数据格式
		 * 
		 */		
		public function addFile(fileId:String, url:String, vars:URLVariables, rate:int, isDisplayObject:Boolean, domain:ApplicationDomain=null,checkPolicyFile:Boolean = false, dataFormat:String = "text"):void
		{
			if (loadIndex != 0)
			{
				files = [];
				loadIndex = 0;
			}
			
			var param:FileParam = new FileParam();
			param.fileId = fileId;
			param.url = url;
			param.vars = vars;
			param.rate = rate;
			param.domain = domain;
			param.checkPolicyFile = checkPolicyFile;
			param.isDisplayObject = isDisplayObject;
			param.dataFormat = dataFormat;
			
			files.push(param);
		}
		
		/**
		 * 获取文件 
		 * 文本类型为：URLLoader
		 * 可视化类型为：Loader
		 * 
		 * @param fileId
		 * @return 
		 * 
		 */		
		public function getFileLoader(fileId:String):Object
		{
			for(var i:int = 0; i<files.length; i++)
			{
				var param:FileParam = files[i];
				if (param.fileId == fileId)
				{
					if (param.isDisplayObject)
						return param.dispLoader;
					else
						return param.urlLoader;
				}
			}
			
			return null;
		}
		
		/**
		 * 获取全部的加载文件
		 * */
		public function getAllFileLoader():Array{
			return files;
		}
		
		private var oneLoader:*;
		/***
		 * 卸载队列前次加载事件
		 * */
		private function delEventListener():void{
			if(oneLoader){
				if(oneLoader is Loader){
					oneLoader.contentLoaderInfo.removeEventListener(Event.COMPLETE, CompleteHandler);
					oneLoader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, IoErrorHandler);
					oneLoader.contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS, ProgressHandler);
					
					oneLoader.unload();
					oneLoader.unloadAndStop();
				}else{
					oneLoader.removeEventListener(Event.COMPLETE, CompleteHandler);
					oneLoader.removeEventListener(IOErrorEvent.IO_ERROR, IoErrorHandler);
					oneLoader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, SecurityErrorHandler);
					oneLoader.removeEventListener(ProgressEvent.PROGRESS, ProgressHandler);
				}
				
				oneLoader=null;
			}
		}
		/**
		 * 开始加载 
		 * 
		 */		
		public function load():void
		{
			if (files.length <= loadIndex)
			{
				dispatchEvent(new Event(Event.COMPLETE));
				return;
			}
			
			var param:FileParam = files[loadIndex++];
			var req:URLRequest;
			var lc:LoaderContext;
						
			req = new URLRequest(param.url);
			
			if (param.vars != null)
				req.data = param.vars;
			
			if (param.isDisplayObject){
				oneLoader = new Loader();
				param.dispLoader = oneLoader;
				
				oneLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, CompleteHandler);
				oneLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, IoErrorHandler);
				oneLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, ProgressHandler);
				
				if (param.domain != null)
				{
					lc = new LoaderContext(param.checkPolicyFile, param.domain);
				}
				
				oneLoader.load(req, lc);
			}else{
				oneLoader = new URLLoader();		
				oneLoader.dataFormat = param.dataFormat;
				param.urlLoader = oneLoader;
				
				oneLoader.addEventListener(Event.COMPLETE, CompleteHandler);
				oneLoader.addEventListener(IOErrorEvent.IO_ERROR, IoErrorHandler);
				oneLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, SecurityErrorHandler);
				oneLoader.addEventListener(ProgressEvent.PROGRESS, ProgressHandler);
				
				oneLoader.load(req);
			}
		}
		
		// 加载完成，则继续加载
		private function CompleteHandler(e:Event):void
		{
			// delEventListener();
			load();
		}
		
		// 加载错误
		private function IoErrorHandler(e:IOErrorEvent):void
		{
			dispatchEvent(e);
		}
		
		// 加载错误
		private function SecurityErrorHandler(e:SecurityErrorEvent):void
		{
			dispatchEvent(e);
		}
		
		// 进度事件
		private function ProgressHandler(e:ProgressEvent):void
		{
			var param:FileParam;
			var bytesLoaded:int;
			var bytesTotal:int;
			
			var totalRate:int=0;
			var loadedRate:int=0;
			
			for(var i:int = 0; i<files.length; i++)
			{
				param = files[i];
				totalRate+=param.rate;
				if (i < loadIndex-1)
					loadedRate += param.rate;
			}
			
			param = files[loadIndex - 1];
			
			var rate:Number = loadedRate / totalRate + (e.bytesLoaded/ e.bytesTotal) * (param.rate / totalRate);
			
			bytesLoaded = rate * 10000;
			bytesTotal = 10000;
			
			var pe:ProgressEvent = new ProgressEvent(ProgressEvent.PROGRESS,false, false, bytesLoaded, bytesTotal);
			
			dispatchEvent(pe);
		}
	}
}

import flash.display.Loader;
import flash.net.URLLoader;
import flash.net.URLVariables;
import flash.system.ApplicationDomain;

/**
 * 加载文件参数 
 * @author rendong01
 * 
 */
class FileParam{
	public var fileId:String;
	public var url:String;
	public var vars:URLVariables;
	public var rate:int;
	public var domain:ApplicationDomain;
	public var isDisplayObject:Boolean;
	public var checkPolicyFile:Boolean;
	public var dispLoader:Loader;
	public var urlLoader:URLLoader;
	public var dataFormat:String;
}